#pragma once
#include <thread>
#include <atomic>

class  CThreadRunLoop {
public:
	virtual ~CThreadRunLoop() {}

	//run in current thread
	virtual void JoinRun() {
		if (m_bRunning) {
			//to do log
			return;
		}
		m_bRunning = true;
		ThreadFun();
	}

	//async Run
	virtual void DeTachRun() {
		if (m_bRunning) {
			//to do log
			return;
		}
		m_bRunning = true;
		m_thread = std::thread(&CThreadRunLoop::ThreadFun, this);
		m_thread.detach();
	}

	//set stop flag
	virtual void Stop() {
		m_bStopFlag = true;
	}

	//check stop flag
	bool IsStoped() {
		return m_bStopFlag;
	}

	virtual bool IsRunning() {
		return m_bRunning;
	}

	virtual void ThreadFun() {
		while (!IsStoped()) {
			Loop();
		}
		if (!OnExit()) {
		}
		m_bRunning = false;
	}

	// must override
public:
	virtual bool Init() = 0;
protected:
	virtual bool Loop() = 0;
	virtual bool OnExit() = 0;

	std::thread m_thread;
	std::atomic<bool> m_bStopFlag = false;
	bool m_bRunning = false;

};
